﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Renci.iRods.Studio.Common.BaseClasses;
using Renci.iRods.Studio.Modules.Explorer.Events;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Prism.Events;
using Renci.iRods.Studio.Common;
using Renci.iRods.Studio.Common.Events;
using Renci.iRods.Studio.Modules.Explorer.Models;
using System.Collections.ObjectModel;

namespace Renci.iRods.Studio.Modules.Explorer.ViewModels
{
    public class UsersDockableViewModel : ViewModelBase
    {
        private SelectedObjectChangedEvent _selectedObjectChangedEvent;

        public ObservableCollection<UserModel> ItemsSource { get; private set; }

        private object _selectedItem;
        public object SelectedItem
        {
            get
            {
                return this._selectedItem;
            }
            set
            {
                this._selectedItem = value;
                this.NotifyOfPropertyChange(() => this.SelectedItem);
                this._selectedObjectChangedEvent.Publish(value);
            }
        }

        public UsersDockableViewModel()
        {
            var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
            var connectionChangedEvent = eventAggregator.GetEvent<ConnectionChnagedEvent>();
            this._selectedObjectChangedEvent = eventAggregator.GetEvent<SelectedObjectChangedEvent>();

            this.OnConnectionChanged(ApplicationState.Current.Connection);

            connectionChangedEvent.Subscribe(OnConnectionChanged);
        }

        private void OnConnectionChanged(IRodsConnection connection)
        {
            if (connection != null)
            {
                this.ItemsSource = new ObservableCollection<UserModel>(from u in connection.Users
                                                                       select new UserModel(connection, u));
            }
            else
            {
                this.ItemsSource = null;
            }

            this.NotifyOfPropertyChange(() => this.ItemsSource);
        }

    }
}
